package com.smarthealthring.mm.ui.activity;

import android.app.AlertDialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.smarthealthring.mm.App;
import com.smarthealthring.mm.R;
import com.smarthealthring.mm.api.ApiRequest;
import com.smarthealthring.mm.base.BaseActivity;
import com.smarthealthring.mm.bean.LoginRes;
import com.smarthealthring.mm.constant.ComConstant;
import com.smarthealthring.mm.contract.LoginContract;
import com.smarthealthring.mm.event.WechatLoginEvent;
import com.smarthealthring.mm.presenter.LoginPresenter;
import com.smarthealthring.mm.utils.ComToolBar;
import com.smarthealthring.mm.utils.ErrorHanding;
import com.smarthealthring.mm.utils.RandomUtil;
import com.smarthealthring.mm.utils.RegexUtils;
import com.smarthealthring.mm.utils.RxBus;
import com.smarthealthring.mm.utils.SPUtils;
import com.smarthealthring.mm.utils.ToastUtil;
import com.smarthealthring.mm.widgets.CleanEditText;
import com.jakewharton.rxbinding2.view.RxView;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.trello.rxlifecycle2.android.ActivityEvent;

import org.reactivestreams.Subscription;

import java.util.HashMap;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import io.reactivex.Flowable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;

import static com.smarthealthring.mm.constant.ComConstant.LOGINTYPE_MSG;
import static com.smarthealthring.mm.constant.ComConstant.LOGINTYPE_PASSWORD;
import static com.smarthealthring.mm.utils.SPUtils.IS_FIRST_LOGIN;
import static com.smarthealthring.mm.utils.SPUtils.TOKEN;
import static com.smarthealthring.mm.utils.SPUtils.USERID;
import static com.smarthealthring.mm.utils.SPUtils.USERNAME;

/**
 * 登录界面
 */
public class LoginActivity extends BaseActivity<LoginPresenter> implements LoginContract.View{
    @BindView(R.id.tv_goto_regist)
    TextView mTvGotoRegist;
    @BindView(R.id.tv_get_verifycode)
    TextView mTvGetVerifyCode;
    @BindView(R.id.tv_phoneno)
    CleanEditText mEtPhoneNo;
    @BindView(R.id.tv_login)
    TextView mTvLogin;
    @BindView(R.id.et_verifycode)
    CleanEditText mEtVerifyCode;
    @BindView(R.id.tv_reset_pwd)
    TextView mTvResetPwd;
    @BindView(R.id.tv_change_type)
    TextView mTvChangeLoginType;
    @BindView(R.id.et_pwd)
    CleanEditText mEtPwd;

    @BindView(R.id.ll_verfifycode_login) //验证码登录
    LinearLayout mLlVerifyLogin;
    @BindView(R.id.ll_pwd_login)  //密码登录
    LinearLayout mLlPwdLogin;
    @BindView(R.id.iv_wechat_login)
    ImageView mIvWechatLogin;

    @Override
    protected void initComToolBar() {
        ComToolBar.setTitle(mContext,"用户注册");
        ImageView ivLeft = ComToolBar.setleftImg(mContext, R.drawable.back_white);
        RxView.clicks(ivLeft)
                .subscribe((Consumer) o -> finish());
    }

    @Override
    protected int getLayout() {
        return R.layout.act_login;
    }

    @Override
    protected void initEventAndData(@Nullable Bundle savedInstanceState) {
        //去注册页面
        RxView.clicks(mTvGotoRegist)
                .subscribe(o -> {
                    startActivity(new Intent(mContext,UserRegistActivity.class));
                });
        //获取短信验证码
        RxView.clicks(mTvGetVerifyCode)
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept(Object o) throws Exception {
                        String phoneNo = mEtPhoneNo.getText().toString().trim();

                        if (TextUtils.isEmpty(phoneNo)) {
                            ToastUtil.shortShow("请输入手机号码");
                            return;
                        }
                        if (!RegexUtils.isMobileExact(phoneNo)) {
                            ToastUtil.shortShow("手机号码格式不正确!");
                            return;
                        }
                        mPresenter.getVerifyCode(new HashMap<String, String>() {{
                            put("trans_id", "1001");
                            put("nonce_str", RandomUtil.getRandomString(32));
                            put("mobile", phoneNo);
                            put("vercodetype", ComConstant.MSG_LOGIN);
                        }});
                        count(); //倒计时
                    }
                });
        
        //登录
        RxView.clicks(mTvLogin)
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept(Object o) throws Exception {
                        String phoneNo = mEtPhoneNo.getText().toString().trim();
                        String password = mEtPwd.getText().toString().trim();
                        String verifyCode = mEtVerifyCode.getText().toString().trim();
                        if (TextUtils.isEmpty(phoneNo)) {
                            ToastUtil.shortShow("请输入手机号码");
                            return;
                        }
                        if (mLlVerifyLogin.getVisibility() == View.VISIBLE && TextUtils.isEmpty(verifyCode)) {
                            ToastUtil.shortShow("请输入验证码");
                            return;
                        }
                        if (mLlPwdLogin.getVisibility() == View.VISIBLE && TextUtils.isEmpty(password)) {
                            ToastUtil.shortShow("请输入密码");
                            return;
                        }
                        mPresenter.login(new HashMap<String, String>() {{
                            put("trans_id", "2002");
                            put("nonce_str", RandomUtil.getRandomString(32));
                            put("username", phoneNo);

                            if(mLlVerifyLogin.getVisibility() == View.VISIBLE) {
                                put("vercodetype", verifyCode);
                                put("logintype", LOGINTYPE_MSG);
                            } else {
                                put("password", password);
                                put("logintype", LOGINTYPE_PASSWORD);
                            }
                        }});
                    }
                });

        //重置密码
        RxView.clicks(mTvResetPwd)
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept(Object o) throws Exception {
                        startActivity(new Intent(mContext,GetBackPwdActivity.class));
                    }
                });

        //切换密码/验证码登录方式
        RxView.clicks(mTvChangeLoginType)
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept(Object o) throws Exception {
                        if(mLlVerifyLogin.getVisibility() == View.VISIBLE) {
                            mLlVerifyLogin.setVisibility(View.GONE);
                            mLlPwdLogin.setVisibility(View.VISIBLE);
                            mTvChangeLoginType.setText("验证码登录");
                        } else {
                            mLlVerifyLogin.setVisibility(View.VISIBLE);
                            mLlPwdLogin.setVisibility(View.GONE);
                            mTvChangeLoginType.setText("密码登录");
                        }
                    }
                });

        //微信登录
        RxView.clicks(mIvWechatLogin)
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept(Object o) throws Exception {
                        //微信登录
                        SendAuth.Req req = new SendAuth.Req();
                        req.scope = "snsapi_userinfo"; //获取个人信息
                        req.state = "wechat_sdk_demo_test";
                        App.getInstance().mWXAPI.sendReq(req);
                    }
                });

        //微信授权成功后  请求服务器的接口拿个人信息
        RxBus.getInstance().tObservable(WechatLoginEvent.class)
                .subscribe(new Consumer<WechatLoginEvent>() {
                    @Override
                    public void accept(WechatLoginEvent event) throws Exception {
                        String code = event.getCode();
                        showLoading(true);
                        mEtPwd.setText(event.getCode());

                        ApiRequest.wechatLogin(new HashMap<String, String>() {{
                            put("trans_id", "2007");
                            put("nonce_str", RandomUtil.getRandomString(32));
                            put("code", code);
                        }})
                                .subscribe(new Consumer<Object>() {
                                    @Override
                                    public void accept(Object o) throws Exception {
                                        dismissLaoding();
                                        startActivity(new Intent(mContext, HomeActivity.class));
                                        finish();
                                    }
                                }, new Consumer<Throwable>() {
                                    @Override
                                    public void accept(Throwable throwable) throws Exception {
                                        dismissLaoding();
                                        ToastUtil.shortShow(ErrorHanding.handleError(throwable));
                                    }
                                });
                    }
                });
    }

    /**
     * 30秒才能发送一次
     */
    private void count() {
        final int time = 60;
        Flowable.interval(0, 1, TimeUnit.SECONDS)
                .compose(this.bindUntilEvent(ActivityEvent.DESTROY))
                .take(time + 1)
                .map(new Function<Long, Long>() {
                    @Override
                    public Long apply(Long aLong) throws Exception {
                        return time - aLong;
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .doOnSubscribe(new Consumer<Subscription>() {
                    @Override
                    public void accept(Subscription subscription) throws Exception {
                        mTvGetVerifyCode.setEnabled(false);
                    }
                })
                .subscribe(new Consumer<Long>() {
                               @Override
                               public void accept(Long num) throws Exception {
                                   mTvGetVerifyCode.setText("剩余" + num + "秒");

                                   if (num == 0) {
                                       mTvGetVerifyCode.setEnabled(true);
                                       mTvGetVerifyCode.setText("发送验证码");
                                   }
                               }
                           }, throwable -> {

                        }
                        , () -> {
                            mTvGetVerifyCode.setEnabled(true);
                            mTvGetVerifyCode.setText("发送验证码");
                        }
                );
    }

    @Override
    protected LoginPresenter createPresenter() {
        return new LoginPresenter();
    }

    @Override
    public void getVerifyCodeSuccess() {

    }

    @Override
    public void getVerifyCodeFail() {

    }

    /**
     * 登录成功&失败
     */
    @Override
    public void loginSuccess(LoginRes response) {
        SPUtils.setString(TOKEN,response.getAccesstoken());
        SPUtils.setString(USERID,response.getUserid());
        SPUtils.setString(USERNAME,response.getUsername());
        boolean isFirst = SPUtils.getBoolean(IS_FIRST_LOGIN, false);
        //跳转个人信息设置界面
//        startActivity(new Intent(mContext,PersonInfoActivity.class));
        if (isFirst) {
            SPUtils.setBoolean(IS_FIRST_LOGIN, true);
            startActivity(new Intent(mContext, PersonInfoActivity.class));
        } else {
            startActivity(new Intent(mContext, HomeActivity.class));
        }
        finish();
    }

    @Override
    public void loginFail() {

    }
}
